home *** CD-ROM | disk | FTP | other *** search
- Path: news.unt.edu!news
- From: Steve Fogoros <sfogoros@hsc.unt.edu>
- Newsgroups: comp.lang.c
- Subject: Re: Determining the length of an int in string form
- Date: Wed, 13 Mar 1996 22:34:53 -0800
- Organization: University of North Texas Health Science Center
- Message-ID: <3147BE0D.296@hsc.unt.edu>
- References: <3146D058.DD7@cbm.com>
- NNTP-Posting-Host: sfogoros.hsc.unt.edu
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win16; I)
-
- Dave Payne wrote:
- >
- > Consider this:
- >
- > I have a variable of type int, and I would like to use the sprintf()
- > function to write this variable to a string. However, I want to
- > dynamically allocate the space for the string, and only malloc enough
- > space to hold the int. Here's a code fragment that may illustrate this
- > more clearly:
- >
-
- Here is what I would do,
-
- char buf[80]; // int could be any length when converted. (Twenty years from now
- // will int be 256 bits? That would be over 80 digits.)
- // In the mean time you should make buf at least buf[12] because
- // int could be 32 bits. For 64 bit use buf[22];
-
- void func1() {
-
- int i = 1234;
- char *a;
-
- sprintf(buf,"%s%d","The value of i is ",i);
- a = malloc(strlen(buf + 1));
- if(!a) get_outta_here("malloc error");
- strcpy(a,buf);
- printf("%s\n",a);
- free(a);
- }
-
-
- --
- Steve Fogoros, Academic Information Coordinator
- University of North Texas Health Science Center
- sfogoros@hsc.unt.edu
-